<?php


namespace App\Services\WechatHandler;

use App\Facades\EasyWechat;
use App\Models\WxComponentVerifyTicket;
use App\Models\WxMpList;
use EasyWeChat\OpenPlatform\Application;

/**
 * 处理微信component_verify_ticket协议推送，将指定app_id的EasyWechat开放平台对象更新verify_ticket
 *
 * @author mingyoung <mingyoungcheung@gmail.com>
 */
class OpenVerifyTicketRefreshedHandler extends BaseEventHandler
{
    /**
     * {@inheritdoc}.
     */
    public function handle($payload = null)
    {
        \Log::info('component_verify_ticket', $payload);
        if (!empty($payload['ComponentVerifyTicket'])) {
            $openPlatform = EasyWechat::openPlatform($this->appid);
            $openPlatform->verify_ticket->setTicket($payload['ComponentVerifyTicket']);
            //保险机制，防止缓存失败无可用Ticket
            try{
                $mpList = WxMpList::where('appid', $this->appid)->first();
                if ($mpList){
                    $mpList->open_verify_ticket = $payload['ComponentVerifyTicket'];
                    $mpList->save();
                }
            }catch (\Exception $e){}
        }
    }
}
